import { ref, shallowRef, toRaw, watchEffect } from 'vue'
import Regist from '@/components/login/registForm.vue'
import Login from '@/components/login/loginForm.vue'
import List from '@/components/login/loginList.vue'
import MsgUps from '@/components/popUps/msgUps.vue'

import { storeToRefs } from 'pinia'
import { useLocalStorageStore } from '@/stores/localStore'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useCurrActStroe } from '@/stores/currActStore'

import { useRouter } from 'vue-router'
import { useModalStore } from '@/stores/modalStore'
import type {
  AsyncReturnLoginData,
  ErrorData,
  FormSuccessData,
  LoginFormDataExport,
  RegistFormDataExport
} from '@/types/loginType'

export default function () {
  const { currUser } = useCurrActStroe()
  const { regist, login } = useAsyncAxios()

  const childRef = ref<RegistFormDataExport | LoginFormDataExport | null>(null)
  const { accounts } = storeToRefs(useLocalStorageStore())

  const { setLocal, removeLocal } = useLocalStorageStore()
  const router = useRouter()
  // 表单组件显示控制
  const componentsControl = shallowRef()
  // 表单切换控制
  const closeBtn = ref(true)
  // 弹窗
  const msgData = ref()
  const { isPops } = storeToRefs(useModalStore())
  const { changeData } = useModalStore()

  watchEffect(() => {
    if (Object.keys(accounts.value).length === 0) {
      componentsControl.value = Login
      closeBtn.value = false
    } else {
      componentsControl.value = List
    }
  })

  // close 绑定函数
  function changeForms() {
    const form = toRaw(componentsControl.value.__name as string)
    // 列表
    if (form === 'loginList') {
      componentsControl.value = Login
      closeBtn.value = false
    }
    // 注册
    if (form === 'registForm') {
      componentsControl.value = Login
      closeBtn.value = false
    }
  }

  //   点击注册
  async function registForm() {
    // 注册提交值
    const form = toRaw(componentsControl.value.__name as string)
    if (form !== 'registForm') {
      componentsControl.value = Regist
      closeBtn.value = true
    } else {
      // 登录操作
      const formData = (childRef.value as RegistFormDataExport).getRegistFormData()
      if (formData.get('username') && formData.get('password') && formData.get('confirm')) {
        // 发起登录请求
        // axios
        console.log(formData)

        const { status, data } = (await regist(formData)) as AsyncReturnLoginData
        if (status === 200) {
          const { token, id, user, img, ...returnData } = data as FormSuccessData
          const { assignCurrUser } = useCurrActStroe()
          // 当前用户状态
          assignCurrUser({ id, name: user, img, ...returnData })

          setLocal({ id, user, img, token })
          // 跳转页面
          changeData({ status: status, data: { msg: '注册成功' } })

          setTimeout(() => {
            router.push('/index')
          }, 800)
        } else {
          // 错误弹窗
          const { msg } = data as ErrorData
          changeData({ status: status, data: { msg: msg } })
        }
      } else {
        // 提示补全表单
        changeData({ status: -1, data: { msg: '补全表单' } })
      }
    }
  }
  // 点击登录
  async function loginForm() {
    // 检测表单值
    const form = toRaw(componentsControl.value.__name as string)
    if (form !== 'loginForm') {
      componentsControl.value = Login
      closeBtn.value = true
    } else {
      const formData = (childRef.value as LoginFormDataExport).getLoginFormData()
      if (formData.get('username') && formData.get('password')) {
        // 发起登录请求
        // axios
        const { status, data } = await login(formData)
        if (status === 200) {
          // 当前用户状态
          const { token, id, user, img, ...returnData } = data as FormSuccessData
          const { assignCurrUser } = useCurrActStroe()
          console.log({ token, id, user, img, ...returnData })

          assignCurrUser({ id, name: user, img, ...returnData })

          // 备份检测
          if (accounts.value.find((act) => act.id === id)) {
            removeLocal(id)
            setLocal({ id, user, img, token })
          } else {
            // 登录备份
            setLocal({ id, user, img, token })
          }
          // 跳转页面
          changeData({ status: status, data: { msg: '登录成功' } })
          setTimeout(() => {
            router.push('/index')
          }, 800)
        } else {
          // 错误弹窗
          changeData({ status: status, data: data as ErrorData })
        }
      } else {
        // 提示补全表单
        changeData({ status: -1, data: { msg: '补全表单' } })
      }
    }
  }

  return {
    MsgUps,
    msgData,
    isPops,
    childRef,
    componentsControl,
    closeBtn,
    changeData,
    changeForms,
    loginForm,
    registForm
  }
}
